import React, { useRef, useState, useEffect } from 'react';
import { Card, Typography, Button, Space, Select, Divider, ColorPicker, Slider, Switch } from 'antd';
import {
  BoldOutlined,
  ItalicOutlined,
  UnderlineOutlined,
  StrikethroughOutlined,
  OrderedListOutlined,
  UnorderedListOutlined,
  AlignLeftOutlined,
  AlignCenterOutlined,
  AlignRightOutlined,
  LinkOutlined,
  PictureOutlined,
  TableOutlined,
  CodeOutlined,
  UndoOutlined,
  RedoOutlined,
  FullscreenOutlined,
  FontSizeOutlined,
  BgColorsOutlined
} from '@ant-design/icons';

const { Title, Paragraph } = Typography;
const { Option } = Select;

const UEditorPlusPage: React.FC = () => {
  const editorRef = useRef<HTMLDivElement>(null);
  const [content, setContent] = useState('');
  const [fontSize, setFontSize] = useState(14);
  const [fontFamily, setFontFamily] = useState('Arial');
  const [textColor, setTextColor] = useState('#000000');
  const [backgroundColor, setBackgroundColor] = useState('#ffffff');
  const [isFullscreen, setIsFullscreen] = useState(false);

  useEffect(() => {
    if (editorRef.current) {
      editorRef.current.innerHTML = `
        <h2>欢迎使用 UEditor Plus</h2>
        <p>这是一个现代化的富文本编辑器，具有以下特点：</p>
        <ul>
          <li><strong>丰富的格式化选项</strong></li>
          <li><em>直观的用户界面</em></li>
          <li><u>强大的编辑功能</u></li>
          <li>支持表格、链接、图片等多媒体内容</li>
        </ul>
        <p>您可以使用上方的工具栏来格式化文本。</p>
      `;
    }
  }, []);

  const execCommand = (command: string, value?: string) => {
    document.execCommand(command, false, value);
    updateContent();
  };

  const updateContent = () => {
    if (editorRef.current) {
      setContent(editorRef.current.innerHTML);
    }
  };

  const handleFontSizeChange = (value: number) => {
    setFontSize(value);
    if (editorRef.current) {
      editorRef.current.style.fontSize = `${value}px`;
    }
  };

  const handleFontFamilyChange = (value: string) => {
    setFontFamily(value);
    execCommand('fontName', value);
  };

  const handleTextColorChange = (color: any) => {
    const colorValue = typeof color === 'string' ? color : color.toHexString();
    setTextColor(colorValue);
    execCommand('foreColor', colorValue);
  };

  const handleBackgroundColorChange = (color: any) => {
    const colorValue = typeof color === 'string' ? color : color.toHexString();
    setBackgroundColor(colorValue);
    execCommand('backColor', colorValue);
  };

  const insertTable = () => {
    const tableHTML = `
      <table border="1" style="border-collapse: collapse; width: 100%; margin: 10px 0;">
        <tr>
          <td style="padding: 8px; border: 1px solid #ddd;">单元格 1</td>
          <td style="padding: 8px; border: 1px solid #ddd;">单元格 2</td>
        </tr>
        <tr>
          <td style="padding: 8px; border: 1px solid #ddd;">单元格 3</td>
          <td style="padding: 8px; border: 1px solid #ddd;">单元格 4</td>
        </tr>
      </table>
    `;
    execCommand('insertHTML', tableHTML);
  };

  const insertLink = () => {
    const url = prompt('请输入链接地址:');
    if (url) {
      execCommand('createLink', url);
    }
  };

  const insertImage = () => {
    const url = prompt('请输入图片地址:');
    if (url) {
      execCommand('insertImage', url);
    }
  };

  const insertCode = () => {
    const code = prompt('请输入代码:');
    if (code) {
      const codeHTML = `<pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; margin: 10px 0;"><code>${code}</code></pre>`;
      execCommand('insertHTML', codeHTML);
    }
  };

  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  const handleGetContent = () => {
    const html = editorRef.current?.innerHTML || '';
    const text = editorRef.current?.innerText || '';
    console.log('UEditor Plus HTML content:', html);
    console.log('UEditor Plus plain text:', text);
  };

  const handleClearContent = () => {
    if (editorRef.current) {
      editorRef.current.innerHTML = '';
      updateContent();
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Title level={2}>UEditor Plus 富文本编辑器</Title>
        <Paragraph>
          UEditor Plus 是 UEditor 的增强版本，提供了更多现代化的功能和更好的用户体验。
        </Paragraph>
        
        <div style={{ marginTop: '20px' }}>
          {/* 工具栏 */}
          <div style={{ 
            padding: '12px', 
            border: '1px solid #d9d9d9', 
            borderRadius: '6px 6px 0 0',
            backgroundColor: '#fafafa',
            display: 'flex',
            flexWrap: 'wrap',
            gap: '8px',
            alignItems: 'center'
          }}>
            {/* 字体设置 */}
            <Select
              value={fontFamily}
              onChange={handleFontFamilyChange}
              style={{ width: 120 }}
              size="small"
            >
              <Option value="Arial">Arial</Option>
              <Option value="Microsoft YaHei">微软雅黑</Option>
              <Option value="SimSun">宋体</Option>
              <Option value="SimHei">黑体</Option>
              <Option value="KaiTi">楷体</Option>
            </Select>
            
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <FontSizeOutlined />
              <Slider
                min={12}
                max={24}
                value={fontSize}
                onChange={handleFontSizeChange}
                style={{ width: 80 }}
              />
              <span style={{ fontSize: '12px', minWidth: '30px' }}>{fontSize}px</span>
            </div>
            
            <Divider type="vertical" />
            
            {/* 文本格式 */}
            <Button
              size="small"
              icon={<BoldOutlined />}
              onClick={() => execCommand('bold')}
            />
            <Button
              size="small"
              icon={<ItalicOutlined />}
              onClick={() => execCommand('italic')}
            />
            <Button
              size="small"
              icon={<UnderlineOutlined />}
              onClick={() => execCommand('underline')}
            />
            <Button
              size="small"
              icon={<StrikethroughOutlined />}
              onClick={() => execCommand('strikeThrough')}
            />
            
            <Divider type="vertical" />
            
            {/* 颜色设置 */}
            <ColorPicker
              value={textColor}
              onChange={handleTextColorChange}
              size="small"
            />
            <ColorPicker
              value={backgroundColor}
              onChange={handleBackgroundColorChange}
              size="small"
            />
            
            <Divider type="vertical" />
            
            {/* 对齐方式 */}
            <Button
              size="small"
              icon={<AlignLeftOutlined />}
              onClick={() => execCommand('justifyLeft')}
            />
            <Button
              size="small"
              icon={<AlignCenterOutlined />}
              onClick={() => execCommand('justifyCenter')}
            />
            <Button
              size="small"
              icon={<AlignRightOutlined />}
              onClick={() => execCommand('justifyFull')}
            />
            
            <Divider type="vertical" />
            
            {/* 列表 */}
            <Button
              size="small"
              icon={<UnorderedListOutlined />}
              onClick={() => execCommand('insertUnorderedList')}
            />
            <Button
              size="small"
              icon={<OrderedListOutlined />}
              onClick={() => execCommand('insertOrderedList')}
            />
            
            <Divider type="vertical" />
            
            {/* 插入功能 */}
            <Button
              size="small"
              icon={<LinkOutlined />}
              onClick={insertLink}
            />
            <Button
              size="small"
              icon={<PictureOutlined />}
              onClick={insertImage}
            />
            <Button
              size="small"
              icon={<TableOutlined />}
              onClick={insertTable}
            />
            <Button
              size="small"
              icon={<CodeOutlined />}
              onClick={insertCode}
            />
            
            <Divider type="vertical" />
            
            {/* 操作按钮 */}
            <Button
              size="small"
              icon={<UndoOutlined />}
              onClick={() => execCommand('undo')}
            />
            <Button
              size="small"
              icon={<RedoOutlined />}
              onClick={() => execCommand('redo')}
            />
            <Button
              size="small"
              icon={<FullscreenOutlined />}
              onClick={toggleFullscreen}
            />
          </div>
          
          {/* 编辑器 */}
          <div
            ref={editorRef}
            contentEditable
            onInput={updateContent}
            style={{
              border: '1px solid #d9d9d9',
              borderTop: 'none',
              borderRadius: '0 0 6px 6px',
              padding: '16px',
              minHeight: isFullscreen ? '70vh' : '400px',
              fontSize: `${fontSize}px`,
              fontFamily: fontFamily,
              outline: 'none',
              lineHeight: '1.6',
              backgroundColor: '#fff'
            }}
          />
        </div>
        
        <div style={{ marginTop: '20px' }}>
          <Space>
            <Button onClick={handleGetContent}>获取内容</Button>
            <Button onClick={handleClearContent}>清空内容</Button>
            <Switch
              checked={isFullscreen}
              onChange={toggleFullscreen}
              checkedChildren="全屏"
              unCheckedChildren="普通"
            />
          </Space>
        </div>
      </Card>
    </div>
  );
};

export default UEditorPlusPage;